<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>

</body>
<script>
	// 定义 Promise 的三种状态常量
	const PENDING = 'pending'
	const FULFILLED = 'fulfilled'
	const REJECTED = 'rejected'
	
	class MyPromise {
		constructor(executor) {
			this.status = PENDING  // 初始状态
			this.value = null      // 保存成功值
			this.reason = null     // 保存失败原因
			this.onFulfilledCallbacks = []  // 成功回调队列（用于异步）
			this.onRejectedCallbacks = []   // 失败回调队列（用于异步）
			
			// 定义 resolve 函数
			const resolve = (value) => {
				if (this.status === PENDING) {
					this.status = FULFILLED
					this.value = value
					// 执行所有成功回调（异步触发）
					this.onFulfilledCallbacks.forEach(fn => fn())
				}
			}
			
			// 定义 reject 函数
			const reject = (reason) => {
				if (this.status === PENDING) {
					this.status = REJECTED
					this.reason = reason
					// 执行所有失败回调（异步触发）
					this.onRejectedCallbacks.forEach(fn => fn())
				}
			}
			
			try {
				// 立即执行 executor（用户传入的函数）
				executor(resolve, reject)
			} catch (err) {
				// 如果执行过程出错，直接 reject
				reject(err)
			}
		}
		
		then(onFulfilled, onRejected) {
			// 处理参数可选的情况
			onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
			onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
			
			// 返回新的 Promise 实现链式调用
			const promise2 = new MyPromise((resolve, reject) => {
				// 封装处理函数
				const handleFulfilled = () => {
					// 使用 setTimeout 模拟微任务（真实 Promise 是微任务）
					setTimeout(() => {
						try {
							const x = onFulfilled(this.value)
							// 处理返回值可能是 Promise 的情况
							this.resolvePromise(promise2, x, resolve, reject)
						} catch (err) {
							reject(err)
						}
					}, 0)
				}
				
				const handleRejected = () => {
					setTimeout(() => {
						try {
							const x = onRejected(this.reason)
							this.resolvePromise(promise2, x, resolve, reject)
						} catch (err) {
							reject(err)
						}
					}, 0)
				}
				
				// 根据当前状态执行不同逻辑
				if (this.status === FULFILLED) {
					handleFulfilled()
				} else if (this.status === REJECTED) {
					handleRejected()
				} else {  // PENDING 状态
					// 将回调存入队列（处理异步情况）
					this.onFulfilledCallbacks.push(handleFulfilled)
					this.onRejectedCallbacks.push(handleRejected)
				}
			})
			
			return promise2
		}
		
		// 处理 Promise 解析过程（符合 Promise/A+ 规范）
		resolvePromise(promise2, x, resolve, reject) {
			// 防止循环引用
			if (promise2 === x) {
				return reject(new TypeError('Chaining cycle detected for promise'))
			}
			
			// 处理 Promise 对象
			if (x instanceof MyPromise) {
				x.then(resolve, reject)
			} else if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
				// 处理 thenable 对象
				let then
				try {
					then = x.then
				} catch (err) {
					return reject(err)
				}
				
				if (typeof then === 'function') {
					let called = false  // 防止重复调用
					try {
						then.call(
							x,
							y => {
								if (!called) {
									called = true
									this.resolvePromise(promise2, y, resolve, reject)
								}
							},
							r => {
								if (!called) {
									called = true
									reject(r)
								}
							}
						)
					} catch (err) {
						if (!called) {
							reject(err)
						}
					}
				} else {
					resolve(x)
				}
			} else {
				resolve(x)
			}
		}
	}
</script>
</html>